package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.mapper.ApUserMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.user.dto.LoginDto;
import com.zhentao.model.user.pojo.ApUser;
import com.zhentao.service.ApUserService;
import com.zhentao.utils.common.AppJwtUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Date 2024/4/28 14:27
 * @Author xdm
 **/

@Service
public class ApUserServiceImpl implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.正常登录 还有游客登录  -有没有输入账号密码
        if (StringUtils.isNotBlank(loginDto.getPhone()) && StringUtils.isNotBlank(loginDto.getPassword())) {
            //1.判断账号是否存在
            QueryWrapper<ApUser> apUserQueryWrapper = new QueryWrapper<>();
            apUserQueryWrapper.lambda().eq(ApUser::getPhone, loginDto.getPhone());
            ApUser apUser = apUserMapper.selectOne(apUserQueryWrapper);
            //账号不存在
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号不存在");
            }

            //2.账号存在 判断密码
            String salt = apUser.getSalt();
            String password = DigestUtils.md5DigestAsHex((loginDto.getPassword() + salt).getBytes());

            if (!password.equals(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
            }

            //3.账号密码都正确  把数据返回给前端 把对象通过jwt加密-》token-->前端

            String token = AppJwtUtil.getToken(apUser.getId().longValue());

            Map<String ,Object> map = new HashMap<>();
            map.put("token",token);
            apUser.setPassword(null); //密码不传递给前端
            apUser.setSalt(null); //slat也不传

            map.put("user",apUser);

            return ResponseResult.okResult(map);


        }else{//游客登录 游客的id默认是0

            String token = AppJwtUtil.getToken(0L);

            Map<String ,Object> map = new HashMap<>();
            map.put("token",token);


            return ResponseResult.okResult(map);
        }


    }
}